/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package interfacegraphique;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import bbqtorrent.InvalidBEncodingException;
import bbqtorrent.TorrentManager;

/**
 *
 * @author CYRIL
 */
public class FenetreAddUrl extends JFrame{

	private JTextField url;
	private JLabel text;
	private JPanel conteneur;
	private JButton ok;	
	private FenetrePrincipale fenetrePrincipale;

	public FenetreAddUrl(FenetrePrincipale fenetrePrincipale){		
		this.fenetrePrincipale = fenetrePrincipale;
		
		this.text = new JLabel();
		this.url = new JTextField();
		this.conteneur = new JPanel();
		this.ok = new JButton("OK");
		//http://ca.isohunt.com/download/316681029/game+of+thrones.torrent

		this.ok.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//Recuperer le fichier torrent a partir de l'url et l'ajouter
				try {
					String urlField = FenetreAddUrl.this.url.getText();
					
					FenetreAddUrl.this.modifyLabel("Téléchargement du fichier en cours...");
										
					if(!urlField.equals("") && urlField.matches("^(http|ftp)://.*\\.torrent/?")) {						
						URL url = new URL(urlField);
						ReadableByteChannel rbc = Channels.newChannel(url.openStream());
						
						String path = "/home/dimitri/file.torrent";
						FileOutputStream fos = new FileOutputStream(path);						
						fos.getChannel().transferFrom(rbc, 0, 1 << 24);
						System.out.println("Fichier dl !");
						
						FenetreAddUrl.this.fenetrePrincipale.addTorrent(path);						
					}
				} catch (IOException e1) {
					new MessageErreur("Impossible de récupérer le fichier distant.");
				} catch (InvalidBEncodingException e1) {
					new MessageErreur("Impossible de lire le fichier.");
				}
				
				FenetreAddUrl.this.dispose();

			}
		});

		this.url.setPreferredSize(new Dimension(190,20));
		
		this.conteneur.add(this.text, BorderLayout.NORTH);
		this.conteneur.add(this.url);
		this.conteneur.add(this.ok, BorderLayout.SOUTH);

		this.add(this.conteneur);
		this.setTitle("Ouvrir via URL");		
		this.modifyLabel("Entrer l'url de votre fichier torrent");
		this.setResizable(false);
		this.setVisible(true);
	}

	public void modifyLabel(String content) {		
		this.text.setText(content);
		this.text.repaint();
		this.setSize(content.length()*8, 127);
		
		this.repaint();
	}

}
